<?php

class News_Exception extends CMS_Exception {}

class News_Category_Exception extends News_Exception {}
class News_Category_Not_Found_Exception extends News_Category_Exception {}

class News_Category {

	protected $id;
	protected $site;
	protected $name;

	public function name(){
		return $this->name;
	}

	public static function GetByID($id){
		$result = Database::getInstance()->query("SELECT * from `news` WHERE `id` = %u AND `site` = %u", $id, Site::getInstance()->GetID());
		if(!($category = $result->fetch_object('News_Category'))){
			throw new News_Category_Not_Found_Exception();
		}
		return $category;
	}

	public function id(){
		return $this->id;
	}

}

class News_Article_Exception extends News_Exception {}
class News_Article_Not_Found_Exception extends News_Article_Exception {}

class News_Article {

	protected $id;
	protected $site;
	protected $category;
	protected $content;
	protected $date;

	public function __construct(){
		$this->content = Content::GetByID($this->content);
	}

	public function id(){
		return $this->id;
	}

	public function title(){
		return $this->content->title();
	}

	public function body(){
		return $this->content->body();
	}

	public function date(){
		return $this->date;
	}

	public function Update($data){
		$this->content->update(array('title' => $data['title'], 'body' => $data['body']));
		$result = Database::getInstance()->query("UPDATE `news_articles` SET `date` = %u WHERE `id` = %u AND `site` = %u", $data['date'], $this->id, Site::getInstance()->GetID());
	}

	public static function GetByCategory($category){
		$result = Database::getInstance()->query("SELECT * from `news_articles` WHERE `category` = %u AND `site` = %u", $category, Site::getInstance()->GetID());
		$articles = array();
		while($article = $result->fetch_object('News_Article')){
			$articles[] = $article;
		}
		return $articles;
	}

	public static function GetByID($id){
		$result = Database::getInstance()->query("SELECT * from `news_articles` WHERE `id` = %u AND `site` = %u", $id, Site::getInstance()->GetID());
		if(!($article = $result->fetch_object('News_Article'))){
			throw new News_Article_Not_Found_Exception();
		}
		return $article;
	}


}
